package cn.dlc.com.filter;

import cn.dlc.com.config.RsaPropertiesConfig;
import cn.dlc.com.pojo.Payload;
import cn.dlc.com.pojo.SysUser;
import cn.dlc.com.utils.JsonUtils;
import cn.dlc.com.utils.JwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author deng
 * @date 2021/6/25 11:15
 **/
public class JwtVerifyFilter extends BasicAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    private RsaPropertiesConfig config;


    public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaPropertiesConfig config) {
        super(authenticationManager);
        this.config = config;
    }

    // 重写认证模块
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        String authorization = request.getHeader("Authorization");
        if(authorization == null || !authorization.startsWith("Bearer ")){
            // 携带的token不正确
            chain.doFilter(request,response);
            //
            try {
                response.setContentType("application/json");
                // 认证失败
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                PrintWriter writer = response.getWriter();

                Map<String,Object> map = new HashMap<>();
                map.put("code",HttpServletResponse.SC_FORBIDDEN);
                map.put("msg","please login");
                writer.write(JsonUtils.toString(map));
                writer.flush();
                writer.close();

            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } else {
            // token格式正确
            String token = authorization.replace("Bearer ","");
            Payload<SysUser> payload = JwtUtils.getInfoFromToken(token, config.getPublicKey(), SysUser.class);
            // 获取用户信息
            SysUser userInfo = payload.getUserInfo();
            if(userInfo!= null) {
                // 验证用户，判断是不是这个而用户和角色，密码不需要了，因为登录的时候没有放进去
                UsernamePasswordAuthenticationToken authResult = new UsernamePasswordAuthenticationToken
                        (userInfo.getUsername(), null, userInfo.getAuthorities());
                // 添加到容器里面(为什么第一次登录的时候不放？)
                SecurityContextHolder.getContext().setAuthentication(authResult);

            } else {
                // 伪造的，token
                System.out.println("error token");
            }
            chain.doFilter(request,response);

        }

    }

}
